package com.guoqing.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

@Slf4j
public final class SyncThreadUtils {

    private SyncThreadUtils() {

    }

    public static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            log.error("thread sleep occur error: ", e);
        }
    }

    public static boolean isLock(RedisTemplate<String, String> redisTemplate, String redisKey, String lockId) {
        boolean isLock = false;
        redisTemplate.opsForValue().setIfAbsent(redisKey, lockId);
        String redisLockId = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isBlank(redisLockId)) {
            redisTemplate.opsForValue().setIfAbsent(redisKey, lockId);
            redisLockId = redisTemplate.opsForValue().get(redisKey);
        }
        if (lockId.equals(redisLockId)) {
            isLock = true;
        }
        return isLock;
    }

    public static void unLock(RedisTemplate<String, String> redisTemplate, String redisKey) {
        redisTemplate.delete(redisKey);
    }

}
